<?php
/**
 * Project: HTPHouDuan
 * User: xilibo
 * Date: 2018/1/24
 */

define('MKEY', 'HPTSecKey(*%@)');
define('JSON_OPTIONS', JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
header('Content-Type: application/json, charset=utf-8');

$act = isset($_REQUEST['act']) ? $_REQUEST['act'] : '';
$ret_data = ['err' => 1];
if (! $act){
	$ret_data['msg'] = '操作无效';
	exit(json_encode($ret_data));
}

require __DIR__ . '/Mcrypter.php';

if ($act == 'example'){
	$str_test = '{"uname":"trump"}';
	$str_in_game = '{"uname":"trump","act":"inGame", "game":"haochepiaoyi"}';
	$str_games = '{"act":"games"}';
	$str_recharge = '{"uname":"trump","act":"recharge","method":"out","ordNo":"181109150102120", "money":100}';
	$str_chk_recharge = '{"uname":"trump","act":"chkRecharge","ordNo":"181109150102120"}';
	$str_balance = '{"uname":"trump","act":"getMoney"}';
	$str_bet_count = '{"uname":"trump","act":"dama","lastTime":"2018-01-01 00:00:01"}';

	$mcrypter = new Mcrypter(MKEY, MCRYPT_3DES, MCRYPT_MODE_ECB);

	$enc_test = $mcrypter->encrypt($str_test);
	echo 'test: ' . $enc_test . PHP_EOL;

	$enc_in_game = $mcrypter->encrypt($str_in_game);
	echo 'inGame: ' . $enc_in_game . PHP_EOL;

	$enc_games = $mcrypter->encrypt($str_games);
	echo 'games: ' . $enc_games . PHP_EOL;

	$enc_recharge = $mcrypter->encrypt($str_recharge);
	echo 'recharge: ' . $enc_recharge . PHP_EOL;

	$enc_chk_recharge = $mcrypter->encrypt($str_chk_recharge);
	echo 'chkRecharge: ' . $enc_chk_recharge . PHP_EOL;

	$enc_balance = $mcrypter->encrypt($str_balance);
	echo 'balance: ' . $enc_balance . PHP_EOL;

	$str_bet_count = $mcrypter->encrypt($str_bet_count);
	echo 'bet count: ' . $str_bet_count . PHP_EOL;

	echo str_repeat('=', 100) . PHP_EOL;

	echo 'test decrypt: ' . $mcrypter->decrypt($enc_test) . PHP_EOL;
	echo 'inGame decrypt: ' . $mcrypter->decrypt($enc_in_game) . PHP_EOL;
	echo 'games decrypt: ' . $mcrypter->decrypt($enc_games) . PHP_EOL;
	echo 'recharge decrypt: ' . $mcrypter->decrypt($enc_recharge) . PHP_EOL;
	echo 'chkRecharge decrypt: ' . $mcrypter->decrypt($enc_chk_recharge) . PHP_EOL;
	echo 'balance decrypt: ' . $mcrypter->decrypt($enc_balance) . PHP_EOL;
	echo 'betcount decrypt: ' . $mcrypter->decrypt($str_bet_count) . PHP_EOL;

	$params = urldecode('8PgXAPidI67ZvPcnau0Hz82YShXIMxwpNmtiMihQImH%2Fx4FBh4dTawjokZexXR7TP4y8A0FxtNeNkckMQTGGzg%3D%3D');
	echo 'params: ' . $params . PHP_EOL;
	echo 'params decrypt: ' . $mcrypter->decrypt($params) . PHP_EOL;
	exit;
}

$secret_key = isset($_POST['secretKey']) ? $_POST['secretKey'] : '';
$text = isset($_POST['plainText']) ? $_POST['plainText'] : '';
$secret_text = isset($_POST['secretText']) ? $_POST['secretText'] : '';
$enc_mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';
$enc_algorithm = isset($_REQUEST['algorithm']) ? $_REQUEST['algorithm'] : '';
$secret_text = str_replace(' ', '+', $secret_text);
$enc_remote_url = isset($_GET['remoeUrl']) ? $_GET['remoeUrl'] : '';
$req_method = isset($_GET['method']) ? $_GET['method'] : '';
$params = isset($_GET['params']) ? $_GET['params'] : [];
$enc_remote_url = str_replace(' ', '+', $enc_remote_url);

$modes = mcrypt_list_modes();
$algorithms = mcrypt_list_algorithms();
$mcrypter = null;

 if ($act == 'list_modes'){
	exit(json_encode($modes));
} else if ($act == 'list_algorithms'){
	exit(json_encode($algorithms));
} else if ($act == 'list_mode_algorithms'){
	$model_algorithms = [];
	$hModule = null;
	foreach ($algorithms as $key => $algorithm) {
		$hModule = @mcrypt_module_open($algorithm, '', $enc_mode, '');
		if (is_resource($hModule)){
			$model_algorithms[] = $algorithm;
		}
	}
	if (is_resource($hModule)) mcrypt_module_close($hModule);
	exit(json_encode($model_algorithms));
} else if ($act == 'catchData'){
	if (empty($enc_remote_url)){
		$ret_data['msg'] = '远程URL不能为空';
		exit(json_encode($ret_data));
	}
	$ret_data['err'] = 0;
	$req_params = ['params' => $params];
	$remote_data = curlRequest($enc_remote_url, $req_method, $req_params);
	$ret_data['msg'] = cleanJsonString($remote_data);
	exit(json_encode($ret_data, JSON_OPTIONS));
} else if ($act == 'encrypt' || $act == 'decrypt'){
	if (empty($secret_key)){
		$ret_data['msg'] = '密钥不能为空';
		exit(json_encode($ret_data));
	}

	if ((! empty($text) || ! empty($secret_text)) && !empty($enc_mode) && !empty($enc_algorithm)){
		$mcrypter = new Mcrypter($secret_key, $enc_algorithm, $enc_mode);
		if ($act == 'encrypt'){
			$encrypted_text = $mcrypter->encrypt($text);
			if($encrypted_text !== false){
				$ret_data['err'] = 0;
				$ret_data['msg'] = $encrypted_text;
				exit(json_encode($ret_data));
			} else {
				$ret_data['msg'] = '加密失败';
				exit(json_encode($ret_data));
			}
		} else if ($act == 'decrypt'){
			$decrypted_text = @$mcrypter->decrypt($secret_text);
			if($decrypted_text !== false){
				$ret_data['err'] = 0;
				$ret_data['msg'] = $decrypted_text;
				exit(json_encode($ret_data));
			} else {
				$ret_data['msg'] = '解密失败';
				exit(json_encode($ret_data));
			}
		}
	} else {
		$ret_data['msg'] = '加密解密参数不正确';
		exit(json_encode($ret_data));
	}
}  


function curlRequest($url, $method = 'GET', $params = [], $headers = [], $timeout = 5){
    $method = strtoupper($method);
    if ($method == 'GET' && !empty($params)){
    	$url .= '&' . http_build_query($params);
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    @curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_POST, $method == 'POST');
    if ($method == 'POST' || $method == 'PUT'){
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    }
    
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

function cleanJsonString($string){
	$data_arr = json_decode($string, true);
	$data_str = json_encode($data_arr, JSON_OPTIONS);
	$data_str = str_replace(["\n", "\r", "\n\r"], '<br>', $data_str);
	$data_str = str_replace(["\\"], '', $data_str);
	$data_str = str_replace([" "], '&nbsp;', $data_str);
	return strval($data_str);
}

